<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Framework\DiServices\Redis;
use Phalcon\Di;
use StarCloud\Library\Exception;
use StarCloud\Library\HttpCurl;
/**
 * AccessToken：2e2O82o14WkxY
SecretKey：4836eccd75f52a550d1c383359e0980f
任务 ID：1443567656205545472
代理商 ID：1735363850399039488
 */

class ZhiHu
{
    use HttpCurl;

    /* @var $httpClient HttpClient */
    private $httpClient = null;
    /* @var $cacheClass Redis */
    protected $cacheClass = null;

    protected $access_token = '2e2O82o14WkxY';
    protected $secretKey = '4836eccd75f52a550d1c383359e0980f';

    protected $taskId = '1443567656205545472';
    protected $agentId = '1735365697578733568';
    protected $channelId = '1735363850399039488';

    const APP_ID_NOVEL = 'novel';
    const APP_ID_YANYAN = 'yanyan';

    const APP_CONFIG = [
        self::APP_ID_NOVEL => [
            'access_token' => '2e2O82o14WkxY',
            'secretKey' => '4836eccd75f52a550d1c383359e0980f',
            'taskId' => '1443567656205545472',
            'channelId' => '1735363850399039488',
        ],
        self::APP_ID_YANYAN => [
            'access_token' => '2e2O82o14WkxY',
            'secretKey' => '4836eccd75f52a550d1c383359e0980f',
            'taskId' => '1710354934426505216',
            'channelId' => '1603362400945717248',
        ],
    ];

    public function __construct($app = self::APP_ID_NOVEL)
    {
        if (!isset(self::APP_CONFIG[$app])) {
            throw new Exception(9999, "zhihu appid is error");
        }
        $config = self::APP_CONFIG[$app];
        $this->access_token = $config['access_token'];
        $this->secretKey = $config['secretKey'];
        $this->taskId = $config['taskId'];
        $this->channelId = $config['channelId'];

        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    protected function sign($params)
    {
        $params['access_token'] = $this->access_token;
        $params['timestamp'] = time();
        ksort($params);
        $str = '';
        foreach ($params as $key => $value) {
            if (!empty($str)) {
                $str .= ('&' . $key . '=' . $value);
            } else {
                $str .= ($key . '=' . $value);
            }
        }
        return hash_hmac('sha256', md5($str), $this->secretKey);
    }

    public function getCategory()
    {
        return [
            ['id' => '1710322868645269504', 'name' => '高订单'],
            ['id' => '1710328690192420864', 'name' => '高转化'],
            ['id' => '1661766472115556352', 'name' => '高评论'],
            ['id' => '1602702307455352832', 'name' => '虐文'],
            ['id' => '1603424564008202240', 'name' => '爽文'],
            ['id' => '1638237687474491392', 'name' => '末日'],
        ];
    }
    /**
     * 分类
     * @return void
     */
    public function contentLabel($app)
    {
        return [
            ['id' => 'hot', 'name' => '知乎官推'],
            ['id' => '1710322868645269504', 'name' => '高订单'],
            ['id' => '1710328690192420864', 'name' => '高转化'],
            ['id' => '1661766472115556352', 'name' => '高评论'],
            ['id' => '1602702307455352832', 'name' => '虐文'],
            ['id' => '1603424564008202240', 'name' => '爽文'],
            ['id' => '1638237687474491392', 'name' => '末日'],
        ];
    }

    public function content($ruleId, $page, $size)
    {
        $url = 'https://open.zhihu.com/alliance/api/vip/rule_contents?';

        $body = [
            'access_token' => $this->access_token,
            'rule_id' => $ruleId,
        ];

        $body['signature'] = $this->sign($body);

        $body['offset'] = intval(($page - 1) * $size);
        $body['limit'] = $size;

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body);

        $json = json_decode($response->getBody()->getContents(), true);

        foreach ($json['data'] as &$item) {
            $item['detail'] = $this->contentDetail($item['id']);
        }

        return $json;
    }

    public function botContent($ruleId, $page, $size)
    {
        $url = 'https://ecom.zhihu.com/alliance/api/vip/rule_contents?';

        $body = [
            'access_token' => $this->access_token,
            'rule_id' => $ruleId,
        ];

        $body['signature'] = $this->sign($body);

        $body['offset'] = intval(($page - 1) * $size);
        $body['limit'] = $size;

        $header = [
          'Cookie' => '_xsrf=DX2Kfpt7csaVNmqIdIej4TKabei09aJS; _zap=b3e17505-1978-4431-b016-0a9813e853b4; d_c0=AMAY34CYxxaPThB5wZ5KMbfvn3Jh0Wto2jw=|1684131763; q_c1=03fc58cb4dd347ac84e22a715804d649|1708323170000|1702907236000; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1708310623,1709190149; z_c0=2|1:0|10:1709190150|4:z_c0|80:MS4xVlBPY0d3QUFBQUFtQUFBQVlBSlZUUVY2eldZa2llak1TNUNDbDhWSERBU3JtRmpkeGhxQVN3PT0=|d1d8519614a1d93e0e8acf6d5a7ea533bf91f92d105aaee9d0b3b70d28fbdfd7; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1709297943; KLBRSID=d6f775bb0765885473b0cba3a5fa9c12|1709606398|1709606372'
        ];

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), [], $header);

//        Di::getDefault()->get('logger')->info(__FUNCTION__ . $response->getBody()->getContents());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data'])) {
            foreach ($json['data'] as &$item) {
                $item['detail'] = $this->contentDetail($item['id']);
            }
            return $json;
        }

        return ['data' => []];
    }

    public function contentDetail($contentId)
    {
        $key = 'zhihu_book_id:' .$contentId;
        $detail = $this->cacheClass->get($key);
        if ($detail) {
            return json_decode($detail, true);
        }

        $url = 'https://open.zhihu.com/alliance/api/vip/rule_content/' . $contentId . '?';
        $body = [
            'access_token' => $this->access_token,
        ];
        $body['signature'] = $this->sign($body);

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body);
        $result = $response->getBody()->getContents();

        $this->cacheClass->set($key, $result, 86400);

        return json_decode($result, true);
    }

    public function getAgentInfo()
    {
        $url = 'https://open.zhihu.com/alliance/api/get_agent_channels?';

        $body = [
            'access_token' => $this->access_token,
        ];
        $body['signature'] = $this->sign($body);

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body);
        $result = json_decode($response->getBody()->getContents(), true);

        return $result;
    }

    public function getPlanTask($page, $size)
    {
        $url = 'https://open.zhihu.com/alliance/api/popularize_tasks?';

        $body = [
            'access_token' => $this->access_token,
            'channel_id' => $this->channelId,
            'timestamp' => time(),
        ];

        $body['signature'] = $this->sign($body);

        $body['offset'] = intval(($page - 1) * $size);
        $body['limit'] = $size;

        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body);

        $json = json_decode($response->getBody()->getContents(), true);

        return $json;
    }

    public function createKeyword($keyword, $content_url)
    {
        $url ='https://open.zhihu.com/alliance/api/popularize_plan?';

        $body = [
            'access_token' => $this->access_token,
            'channel_id' => $this->channelId,
            'task_id' => $this->taskId,
            'timestamp' => time(),
            'popularize_type' => 0,
            'content_url' => $content_url,
            'keyword' => $keyword,
        ];

        $body['signature'] = $this->sign($body);

        $header['Content-Type'] = 'application/json';

        $response = $this->httpClient->sendPostRequest($url, $body, $header);

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data']['plan_id'])) {
            return  $json['data']['plan_id'];
        }

        throw new Exception(9999, $json['error']['message']);
    }


    public function bindPost($planId, $media_account, $media_type, $composition_type,$composition_url, $release_time)
    {
        $url ='https://open.zhihu.com/alliance/api/popularize_composition?';

        $body = [
            'access_token' => $this->access_token,
            'channel_id' => $this->channelId,
            'plan_id' => $planId,
            'timestamp' => time(),
            'media_account' => $media_account,
            'media_type' => $media_type,
            'composition_type' => intval($composition_type),
            'composition_url' => $composition_url,
            'release_time' => $release_time,
        ];

        Di::getDefault()->get('logger')->info(__FUNCTION__ . json_encode($body));

        $body['signature'] = $this->sign($body);

        $header['Content-Type'] = 'application/json';

        $response = $this->httpClient->sendPostRequest($url, $body, $header);

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data']['composition_id'])) {
            return  $json['data']['composition_id'];
        }

        throw new Exception(9999, $json['error']['message'] .'error');
    }

    public function timeData()
    {
        $url = 'https://open.zhihu.com/alliance/api/data_report/real_time_data?';

        $body = [
            'access_token' => $this->access_token,
            'type' => 1,
            'time_scale' => 1,
            'timestamp' => time(),
            'fields' => 'search_num,order_num,created_at'
        ];

        $body['signature'] = $this->sign($body);


        $response = $this->httpClient->sendGetRequest($url . http_build_query($body), $body);

        $json = json_decode($response->getBody()->getContents(), true);

        return $json;
    }
}

